#define _CRT_SECURE_NO_WARNINGS 1

#include "seqlist.h"

void SLInit(SList* psl)
{
	assert(psl);
	psl->size = 0;
	psl->capacity = 0;
	psl->data = NULL;
}

void SLPrint(const SList* psl)
{
	assert(psl);
	int i = 0;
	for (i = 0; i < psl->size; i++)
	{
		printf("%d ", psl->data[i]);
	}
	printf("\n");

}

void CheckCapacity(SList* psl)
{
	assert(psl);
	if (psl->size < psl->capacity)
		return;
	size_t newcapacity = psl->capacity == 0 ? 3 : psl->capacity * 2;
	SLDataType* tmp = (SLDataType*)realloc(psl->data, newcapacity * sizeof(SLDataType));
	if (tmp == NULL)
	{
		perror("CHeckCapacity::realloc");
		return;
	}
	psl->capacity = newcapacity;
	psl->data = tmp;
}

void SLPushBack(SList* psl, SLDataType x)
{
	assert(psl);
	CheckCapacity(psl);
	psl->data[psl->size] = x;
	psl->size += 1;
}

void SLPopBack(SList* psl)
{
	assert(psl);
	if(psl->size > 0)
		psl->size -= 1;
}

void SLPushFront(SList* psl, SLDataType x)
{
	assert(psl);
	CheckCapacity(psl);
	for (int n = psl->size; n > 0; n--)
	{
		psl->data[n] = psl->data[n - 1];
	}
	psl->data[0] = x;
	psl->size += 1;
}

void SLPopFront(SList* psl)
{
	assert(psl);
	if (psl->size < 2)
	{
		psl->size = 0;
		return;
	}
	for (int i = 0; i < psl->size - 1; i++)
	{
		psl->data[i] = psl->data[i + 1];
	}
	psl->size--;
}


int SLFind(SList* psl, SLDataType x)
{
	assert(psl);

	for (int i = 0; i < psl->size; i++)
	{
		if (psl->data[i] == x)
		{
			return i;
		}
	}
	return -1;
}

void SLInsert(SList* psl, size_t pos, SLDataType x)
{
	assert(psl);
	if (pos >= psl->size)
	{
		SLPushBack(psl, x);
		return;
	}
	else if (pos <= 0)
	{
		SLPushFront(psl, x);
		return;
	}
	CheckCapacity(psl);
	for (int i = psl->size; i > pos; i--)
	{
		psl->data[i] = psl->data[i - 1];
	}
	psl->data[pos] = x;
	psl->size++;
}

void SLErase(SList* psl, size_t pos)
{
	assert(psl);
	if (pos < 0 || pos >= psl->size)
	{
		return;
	}
	for (int i = pos; i < psl->size - 1; i++)
	{
		psl->data[i] = psl->data[i + 1];
	}
	psl->size--;
}

void SLDestory(SList* psl)
{
	assert(psl);
	free(psl->data);
	psl->data = NULL;
	psl->size = 0;
	psl->capacity = 0;
}